<?php


namespace PKApp\Form\Classes;

use PKApp\Model\Classes\TraitModel;
use PKApp\Site\Classes\SiteController;
use PKFrame\DataHandler\Arrays;
use PKFrame\DataHandler\Numbers;

class FormTemplateTag extends SiteController
{
    use TraitModel;

    protected $id_model;
    protected $entity_model;

    public function field($params_tpl): array
    {
        $this->id_model = Arrays::GetKey('id', $params_tpl, 'Model_IdEmpty', 'model');
        Numbers::IsId($this->id_model) ?: $this->noticeByPage('Model_IdEmpty', null, 'model');
        $this->_isFormModel();
        return [
            'formFieldList' => $this->_getFieldList(),
        ];
    }

    private function _isFormModel()
    {
        $this->entity_model = $this->serviceOfField()->ServiceByModel()->interface_getEntityById($this->id_model);
        Arrays::GetKey('modelType', $this->entity_model) == 'form' ?: $this->noticeByPage('ModelForm_TypeError', null, 'form');
    }

    private function _getFieldList(): array
    {
        $list = $this->serviceOfField()->GetListByModelId($this->id_model);
        Arrays::Is($list) ?: $this->noticeByPage('fieldList_Empty');
        return $this->_fetchField($list);
    }

    private function _fetchField($list_field): array
    {
        $result = [];
        $service_option = $this->serviceOfOptions();
        foreach ($list_field as $index_field => $item_field) {
            $setting = Arrays::Unserialize($item_field['setting']);
            if ($item_field['formType'] == 'option') {
                $setting_new = [
                    'type_box' => Arrays::GetKey('boxType', $setting),
                    'id_option' => Arrays::GetKey('option', $setting),
                ];
                Arrays::GetKey($setting_new['type_box'], dict('options_type', 'model'),
                    'setting_boxType_error', 'nodel');
                $setting_new['list_option'] = $service_option->GetList(['parentId' => $setting_new['id_option']], ['id', 'name']);
                !Arrays::Is($setting_new['list_option']) ?: $setting_new['list_option'] = Arrays::Column($setting_new['list_option'],'name','id');
                $setting = $setting_new;
            }
            $result[] = [
                'field' => $item_field['field'],
                'name' => $item_field['name'],
                'htmlCode' => out()->tpl($item_field['field'])
                    ->SetTplDir('form')
                    ->SetTplParamList([
                        'id' => $item_field['id'],
                        'formType' => $item_field['formType'],
                        'field' => $item_field['field'],
                        'name' => $item_field['name'],
                        'setting' => $setting,
                    ])->PhpDisplay('form_control'),
            ];
        }
        return $result;
    }

    public function Main()
    {
    }
}
